import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class ChatListenThread implements Runnable {

	private ServerSocket ss;
	private Map<Socket, DataOutputStream> outputStreams = new HashMap<Socket, DataOutputStream>();
	private int port;

	public ChatListenThread(int port) {
		this.port = port;
	}

	public void run() {
		try {
			ss = new ServerSocket(port);
			System.out.println("Listening on " + ss + " and ready to chat");
			while (true) {
				System.out.println("Listening...");
				Socket s = ss.accept();
				System.out.println("Connection from " + s.getInetAddress().getHostAddress());

				DataOutputStream dout = new DataOutputStream(s
						.getOutputStream());
				outputStreams.put(s, dout);

				new Thread(new ChatWorkerThread(this, s)).start();
			}
		} catch (IOException e) {
			System.err.println("ChatListenThread.run: IOException " + e);
			e.printStackTrace();
		}
	}

	protected void sendToAll(String message) {
		synchronized (outputStreams) {
			for (DataOutputStream dout : outputStreams.values()) {
				try {
					dout.writeUTF(message);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	protected void removeConnection(Socket s) {
		synchronized (outputStreams) {
			System.out.println("Removing connection to " + s);
			outputStreams.remove(s);
			try {
				s.close();
			} catch (IOException e) {
				System.err.println("Error closing " + s);
				e.printStackTrace();
			}
		}
	}

}
